package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.EventRecordDao;
import com.wlhse.entity.EventRecordPojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.EventRecordService;
import com.wlhse.util.HashUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class EventRecordServiceImpl implements EventRecordService {

    @Resource
    private EventRecordDao eventRecordDao;

    @Value("${RESOURCES_URL}")
    private String url;

    @Override
    @Transactional
    public String addEventRecord(EventRecordPojo eventRecordPojo) {
        String hash = HashUtil.hash(eventRecordPojo.getEventRecordName() + eventRecordPojo.getCheckDate() + eventRecordPojo.getAddress());
        eventRecordPojo.setHash(hash);
        if (eventRecordDao.addEventRecord(eventRecordPojo) <= 0)
            throw new WLHSException("新增失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String deleteEventRecord(Integer id) {
        if (eventRecordDao.deleteEventRecord(id) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String updateEventRecord(EventRecordPojo eventRecordPojo) {
        if (eventRecordDao.updateEventRecord(eventRecordPojo) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();

    }

    @Override
    public String queryEventRecord(EventRecordPojo eventRecordPojo) {
        eventRecordPojo.setUrl(url);
        List<EventRecordPojo> list;
        //封装一个和时间有关的包
//        if (StringUtils.isNotBlank(eventRecordPojo.getStartDate()) && StringUtils.isBlank(eventRecordPojo.getEndDate())) {
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//            eventRecordPojo.setEndDate(df.format(new Date()));// new Date()为获取当前系统时间
//        }
        if ("all".equals(eventRecordPojo.getType()))
            return NR.r(eventRecordDao.queryEventRecords(eventRecordPojo));
        else {
            int total = eventRecordDao.queryEventRecordsCount(eventRecordPojo);
            PageHelper.startPage(eventRecordPojo.getPageIdx(), eventRecordPojo.getPageSize());
            list = eventRecordDao.queryEventRecords(eventRecordPojo);
            return NR.r(list, total, eventRecordPojo.getPageIdx());
        }
    }

    @Override
    public String queryEventRecordById(int id) {
        return NR.r(eventRecordDao.queryEventRecordsById(id, url));
    }
}
